package java6699.task;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.Scanner;
import java.util.function.Consumer;

public class Editor6699Controller {
    private File currentFile;
    private SimpleBooleanProperty isChange;
    private Alert alert;
    private FileChooser fc;

    @FXML
    private TextField tfFilename;

    @FXML
    private TextArea taText;

    @FXML
    private void initialize(){
        //监听TextArea的Text属性被修改的事件
        taText.textProperty().addListener((v1,v2,v3)->isChange.set(true));
        //初始化修改标记
        isChange=new SimpleBooleanProperty(false);
        //初始化Alert
        alert=new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("文本编辑器提示");
        alert.getButtonTypes().setAll(
                ButtonType.YES,
                ButtonType.NO,
                ButtonType.CANCEL
        );
        //初始化选择文件
        fc=new FileChooser();
        fc.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("文本文件","*.txt"),
                new FileChooser.ExtensionFilter("Java文件","*.java"),
                new FileChooser.ExtensionFilter("所有","*.*")
        );
    }
    //为CloseRequest注册监听
    public void setCloseRequest(Stage stage){
        //关闭窗口前的事件
        stage.setOnCloseRequest(this::beforeClose);
        //一修改在窗口的标题上加*号,表示内容修改
        isChange.addListener((v1,v2,newValue)->stage.setTitle("文本编辑器"+(newValue ?"*":"")));
    }
    //窗口关闭前的处理
    private void beforeClose(WindowEvent event){
        //如果TextArea的内容已经被修改
        if(isChange.get()){
            String title=currentFile==null ? "?" : ("到"+currentFile+"?");
            alert.setHeaderText("关闭窗口前,是否将为存盘的修改保存"+title);
            //弹出提示
            Optional<ButtonType> type=alert.showAndWait();
            type.ifPresent(new Consumer<ButtonType>() {
                @Override
                public void accept(ButtonType buttonType) {
                    //保存
                    if(buttonType==ButtonType.YES){
                        saveFile(null);
                    }//不保存
                    else if(buttonType==ButtonType.NO){

                    } //取消
                    else {
                        event.consume();
                    }
                }
            });
        }
    }
    //打开新文件前,处理已修改但未保存的内容,处理后才能打开新文件
    private boolean beforeOpenCheck(){
        boolean isopen=true;
        if(isChange.get()){
            String title=currentFile==null ? "?" :("到"+currentFile+"?");
            alert.setHeaderText("打开新文件前,是否将未存盘的修改保存"+title);
            Optional<ButtonType> type=alert.showAndWait();
            if(type.isPresent()){
                ButtonType buttonType=type.get();
                //先保存在打开
                if(buttonType==ButtonType.YES){
                    saveFile(null);

                }//不保存直接打开
                else if(buttonType==ButtonType.NO){

                }//取消打开的动作
                else {
                    isopen=false;
                }
            }
        }
        return isopen;
    }
    //将文件内容显示到TextArea
    private void open(File file) throws FileNotFoundException {
        try(Scanner reader=new Scanner(file)){
            StringBuilder sBuilder=new StringBuilder();
            while (reader.hasNextLine()){
                sBuilder.append(reader.nextLine()).append(System.lineSeparator());
            }
            taText.setText(sBuilder.toString());
        }catch (FileNotFoundException e){
            throw e;
        }
    }
    @FXML
    void openFile(ActionEvent event) throws FileNotFoundException {
        //检查是否有没有保存的修改
        if(!beforeOpenCheck()){
            return;
        }
        setFileChooser("打开");
        File newFile=fc.showOpenDialog(new Stage());
        //如果没有要打开的文件,保持原样
        if(newFile!=null){
            currentFile=newFile;
            tfFilename.setText(currentFile.toString());
            //读取文件显示到TextArea
            open(currentFile);
            //重置修改状态
            isChange.set(false);
        }

    }
    //将修改的内容写入指定文件
    private void save(File file){
        if(file==null) return;
        try(PrintWriter pw=new PrintWriter(file)){
            pw.print(taText.getText());
            isChange.set(false);
            currentFile=file;
            tfFilename.setText(currentFile.toString());
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }

    @FXML
    //另存
    void saveAsFile(ActionEvent event) {
        setFileChooser("另存为");
        //返回选择中的文件
        File asFile=fc.showSaveDialog(new Stage());
        save(asFile);

    }

    @FXML
    //保存
    void saveFile(ActionEvent event) {
        if(currentFile==null){
            setFileChooser("保存为");
            File file=fc.showSaveDialog(new Stage());
            save(file);
        }else {
            save(currentFile);
        }

    }
    //设置文本对话框的标题和初始目录
    private void setFileChooser(String title){
        fc.setTitle(title);
        if(currentFile==null){
            fc.setInitialDirectory(new File("."));
        }else {
            fc.setInitialDirectory(currentFile.getParentFile());
        }
    }

}
